const mongoose = require("mongoose");

// 获取订单
const getOrder = async ({ curPage, eachPage }) => {
    const orderModel = mongoose.model("order");
    const moviesModel = mongoose.model("movies");
    const cinemasModel = mongoose.model("cinemas");
    const theatersModel = mongoose.model("theaters");
    const seatsModel = mongoose.model("seats");

    // 转换类型
    (curPage = ~~curPage), (eachPage = ~~eachPage);
    const data = {
        total: 0,
    }
    // 获取当前model映射的那个集合里存在的文档总数
    data.total = await orderModel.countDocuments();
    // 获取总页数
    data.maxPage = Math.ceil(data.total / eachPage);
    const skipNum = (curPage - 1) * eachPage;
    let order = await orderModel.find().populate("schedulesId").populate("seatingsId").skip(skipNum).limit(eachPage).sort({ _id: -1 }).exec();
    if (order.length == 0) return;
    data.rows = [];
    for (let i = 0; i < order.length; i++) {
        const cinemaData = await cinemasModel.findOne({ _id: order[i].schedulesId.cinemasId });
        const theaterData = await theatersModel.findOne({ _id: order[i].schedulesId.theaterId });
        const movieData = await moviesModel.findOne({ _id: order[i].schedulesId.movieId });
        const showTime = order[i].schedulesId.showTime;
        const price = order[i].schedulesId.price;
        const seat = await seatsModel.findOne({ _id: order[i].seatingsId.seatId });
        const userId = order[i].userId;
        data.rows.push({
            cinemaData,
            theaterData,
            movieData,
            showTime,
            price,
            seat,
            userId,
        });
    }
    return data;

}



module.exports = {
    getOrder
};